package com.mofabot.scheduled

import cn.hutool.core.util.ReUtil
import com.mofabot.bot.BotApp
import com.mofabot.utils.RedisUtil
import org.jsoup.Jsoup
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import us.codecraft.xsoup.Xsoup


/**
 * @author Created by 😁ll😁
 * @since : 2023/6/8.
 */
@Component
class PostPush {

    @Autowired
    private lateinit var bot: BotApp

    @Autowired
    private lateinit var redisUtil: RedisUtil

    private val KEY = "tid:"

    //    @Scheduled(cron = "*/10 * * * * ?")
//    @Scheduled(cron = "* */5 * * * ?")
    fun push() {
        val doc = Jsoup.connect("https://www.xiubbs.com/").get()
        val xElements = Xsoup.compile("//*[@class=\"loading_list cl\"]//div[@class=\"v2_title\"]").evaluate(doc)
        xElements.elements.forEach {
            val per = Xsoup.select(it, "/div/a")

            val tid = ReUtil.get("t-(\\d*?)-", per.elements[0].attr("href"), 1)
            if (!redisUtil.hasKey(KEY + tid)) {
                redisUtil.set(KEY + tid, tid)
                val title = per.elements[0].text()
                val author = per.elements[1].text()
                println(cmsg(author, title, per.elements[0].attr("href")))
                bot.sendMessage(-1001752604232, cmsg(author, title, per.elements[0].attr("href")))
            }
        }
    }

    private fun cmsg(author: String, title: String, url: String): String {
        return "标题：$title \n" +
                "作者：$author \n" +
                "链接：$url \n"
        ;
    }
}
